package com.ishadows.notebook;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.RectF;
import android.net.Uri;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ImageButton;
import android.widget.PopupWindow;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;

import com.ishadows.notebook.model.TransitNoteModel;
import com.note.widget.SVGEditor;
import com.notepad.pages.ColorPickerView;
import com.notepad.pages.ColorView;
import com.notepad.pages.OnColorChangedListener;
import com.notepad.pages.OnColorViewClickListener;
import com.notepad.pages.PageEditSettingHelper;
import com.notepad.pages.PageView;
import com.uosit.widget.InkEditor.OnSizeChangedListener;
import com.uosit.widget.inkEditor.InkContext;

public class EditNoteActivity extends Activity {
	private static int CHANGE_NOTE=0x1001;
	public static final String ScratchPaper="1";
	public static final String UploadWork="2";
	Uri mBatchUri;
    public Bitmap mBitmap;
    //----------------------------------------------------------------- pen data
	private Button penSetting;
    protected SVGEditor mSvgEditor; 
	private static boolean penSettingFlag = false;
	private PopupWindow popupWin;
	private View winView;
	private ImageButton strokes[] = new ImageButton[5];//pen
	private CheckBox checkBoxes[] = new CheckBox[5];
	public static int selected = 0;
	private SeekBar sb;
	private Button wiper;
	private static boolean wiperFlag = false;
	private ColorView cusColor;
	private ColorPickerView colorPicker;
	// ------------------------------------------------------------ Override methods

	
	
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
    	//this.setTheme(getIntent().getIntExtra("theme", R.style.Transparent));
    	super.onCreate(savedInstanceState);
        //setContentView(R.layout.main);
            setContentView(R.layout.edit_note);
         //增加换笔功能
        	penSetting = (Button)findViewById(R.id.pen_setting_btn);
    		penSettingFlag = penSetting.isSelected();
        	penSetting.setOnClickListener(new OnClickListener(){
    			@Override
    			public void onClick(View v) {
    				// TODO Auto-generated method stub
    				penSettingFlag = !penSettingFlag;
    				initPenSetting(v);
    				penSetting.setSelected(penSettingFlag);
    			}
    		});
        	
    		//LayoutInflater mlayoutInflater = PageView.mPageEdit.getLayoutInflater();
    		LayoutInflater mlayoutInflater = LayoutInflater.from(this);
    		winView = mlayoutInflater.inflate(R.layout.font_menu_view, null,false);
    		popupWin = new PopupWindow(winView,222,636);
    		popupWin.setOutsideTouchable(true);
       
    	
    		sb = (SeekBar)winView.findViewById(R.id.seekBar);
    		sb.setProgress(PageView.seekBars[PageView.selected]);
    		colorPicker = (ColorPickerView)winView.findViewById(R.id.colorPicker);
    		wiper = (Button) findViewById(R.id.stroke_changed);
    		
    		wiperFlag = wiper.isSelected();
    		InkContext.getInstance().setSw(wiperFlag);
    		
    		strokes[0] = (ImageButton) winView.findViewById(R.id.panel_btn_pencil);
    		strokes[1] = (ImageButton) winView.findViewById(R.id.panel_btn_ballpoint);
    		strokes[2] = (ImageButton) winView.findViewById(R.id.panel_btn_pen);
    		strokes[3] = (ImageButton) winView.findViewById(R.id.panel_btn_brush);
    		strokes[4] = (ImageButton) winView.findViewById(R.id.panel_btn_markpen);
    		strokes[PageView.selected].setSelected(true);
    		
    		checkBoxes[0] = (CheckBox) winView.findViewById(R.id.checkbox_1);
    		checkBoxes[1] = (CheckBox) winView.findViewById(R.id.checkbox_2);
    		checkBoxes[2] = (CheckBox) winView.findViewById(R.id.checkbox_3);
    		checkBoxes[3] = (CheckBox) winView.findViewById(R.id.checkbox_4);
    		checkBoxes[4] = (CheckBox) winView.findViewById(R.id.checkbox_5);
    		
    		cusColor = (ColorView)winView.findViewById(R.id.nearColor);		
    		
    		for(int i=0; i < strokes.length; i++){
    			strokes[i].setOnClickListener(new OnClickListener() {
    				@Override
    				public void onClick(View view) {
    					for(int j=0;j<strokes.length;j++){
    						if(strokes[j]!=null && view.getId() == strokes[j].getId()){
    							PageView.selected = j;
    							PageEditSettingHelper.setIntPreference(getBaseContext(), PageView.STROKE_TYPE, j);
    							strokes[j].setSelected(true);
    							sb.setProgress(PageView.seekBars[j]);
    							//PageView.mPageEdit.onStrokeWidthChanged();
    						    mSvgEditor.setStrokeWidth(getRealStrokeWidth());
    							//Analyze.onEvent(getBaseContext(), Analyze.EVENT_STROKE_SETTING);
    							wiper.setSelected(false);
    							wiperFlag = false;
    							InkContext.getInstance().setSw(wiperFlag);
    						}else if(strokes[j]!=null){
    							strokes[j].setSelected(false);
    						}
    					}
    					InkContext.getInstance().setSw(false);
    				}
    			});
    		}
    		
    		
    		for(int i=0; i < checkBoxes.length; i++){
    			checkBoxes[i].setOnClickListener(new OnClickListener() {
    				@Override
    				public void onClick(View view) {
    					for(int j=0; j<checkBoxes.length;j++){
    						if(checkBoxes[j] != null && checkBoxes[j].getId() == view.getId()){
    							checkBoxes[j].setChecked(true);
    							//PageView.mPageEdit.onDrawingColorChanged(PageView.checkBoxesColor[j]);
    							
    							mSvgEditor.setDrawingColor(PageView.checkBoxesColor[j]);
    							
    							PageView.near_use_color = PageView.checkBoxesColor[j];
//    							near_default_use_color = checkBoxesColor[j];
    							PageEditSettingHelper.setIntPreference(getBaseContext(),PageView.COLOR_PRE,j);
    						}else if(checkBoxes[j] != null){
    							checkBoxes[j].setChecked(false);
    						}
    					}
    				}
    			});
    		}
    		
    		colorPicker.setOnChangedListener(new OnColorChangedListener(){
    			@Override
    			public void colorChanged(int color) {
    				PageView.near_use_color = color;
    				PageView.near_cus_color = color;
    				cusColor.setShowColor(color);
    				setDefaultColorUnSelectd();
    				//PageView.mPageEdit.onDrawingColorChanged(color);
    				
    				mSvgEditor.setDrawingColor(color);
    			}
    		});
    		
    		cusColor.setOnColorViewClickListener(new OnColorViewClickListener(){
    			@Override
    			public void onClick(int color) {
    				// TODO Auto-generated method stub
    				//PageView.mPageEdit.onDrawingColorChanged(color);
    				mSvgEditor.setDrawingColor(color);
    				setDefaultColorUnSelectd();
    			}
    		});
    		
    		sb.setOnSeekBarChangeListener(new OnSeekBarChangeListener(){

    			@Override
    			public void onProgressChanged(SeekBar seekBar, int progress,
    					boolean fromUser) {
    				// TODO Auto-generated method stub
    				
    			}

    			@Override
    			public void onStartTrackingTouch(SeekBar seekBar) {
    				// TODO Auto-generated method stub
    				
    			}

    			@Override
    			public void onStopTrackingTouch(SeekBar seekBar) {
    				// TODO Auto-generated method stub
    				PageView.seekBars[PageView.selected] = seekBar.getProgress();
    				//PageView.mPageEdit.onStrokeWidthChanged(getRealStrokeWidth());
    				mSvgEditor.setStrokeWidth(getRealStrokeWidth());
    			}
    			
    		});
    		
           
    		// SVG editor
    		mSvgEditor = (SVGEditor)findViewById(R.id.svg_editor);
    		mSvgEditor.setOnSizeChangeListener(new OnSizeChangedListener() {

    			@Override
    			public void onSizeChanged(int w, int h, int oldw, int oldh) {
    				 initData();
    				mSvgEditor.activate();
    				mSvgEditor.setCacheable();
    				mSvgEditor.getSVGBrowser().setCanvasSize(w, h);
    				
    				
    			}
    		});
            
           
            InkContext.getInstance().setSw(false);
            mSvgEditor.setStrokeWidth(3.0f);
            
            wiper.setOnClickListener(new OnClickListener() {

    			@Override
    			public void onClick(View v) {
    				if(InkContext.getInstance().isSw()){
    					InkContext.getInstance().setSw(false);
    					wiper.setBackgroundResource(R.drawable.change_do_pen);
    				}else{
    					InkContext.getInstance().setSw(true);
    					wiper.setBackgroundResource(R.drawable.change_do_eraser);
    				}
    			}
    		});
           
            
   }
    
    private void initData(){
    	initEditor();
    	loadNoteFromIntent();
    }
    
	//wangl
	private Float getRealStrokeWidth(){
		int strokeSelected = PageEditSettingHelper.getIntPreference(getBaseContext(),PageView.STROKE_TYPE, 2);
		int progressValue = PageView.seekBars[strokeSelected];
		if(progressValue == 0 ){
			progressValue = 1;
		}
		return PageView.strokeWidth[strokeSelected] * progressValue/30;
	}
    
	private void setDefaultColorUnSelectd(){
		for(int i = 0; i < 5; i++){
			checkBoxes[i].setChecked(false);
		}
	}
    
	private void initPenSetting(View target){
		
		if(popupWin != null && popupWin.isShowing()){
			popupWin.dismiss();
			return;
		}
		

		if(!popupWin.isShowing()){
			popupWin.showAsDropDown(target, -50, 0);
			popupWin.setFocusable(true);
			popupWin.update();
			popupWin.getContentView().setOnTouchListener(new OnTouchListener(){

				@Override
				public boolean onTouch(View v, MotionEvent event) {
					popupWin.setFocusable(false);
					popupWin.dismiss();
					penSettingFlag = false;
					penSetting.setSelected(penSettingFlag);
					return true;
				}
			});
		}
	}

    
    @Override
    protected void onDestroy() {
        super.onDestroy();

        if (mSvgEditor != null)
        	mSvgEditor.dispose();

        if (mBitmap != null) {
        	mBitmap.recycle();
        	mBitmap = null;
        }
    }
	
	
	private void initEditor() {
		mSvgEditor.clearSelection();
		int width = mSvgEditor.getWidth();
		int height = mSvgEditor.getHeight();
		mSvgEditor.newSvgDocument(width, height);
		mSvgEditor.flush(new RectF(0, 0, width, height));
		mSvgEditor.invalidate();
	}
	
	public void quit(View view){
		byte []paint =mSvgEditor.getSVGBrowser().serialize();
		Bitmap  bitmap =mSvgEditor.getSVGBrowser().getBitmap(null);
		Intent intent =new Intent();
		TransitNoteModel note =TransitNoteModel.getTransitNoteModel();
		note.setContent(paint);
		note.saveImg(bitmap);
		note.save();
		setResult(RESULT_OK, intent);
		finish();
	}
	
	public void clearPaint(View view){
		initEditor();
		System.gc();
	}
	
	private void loadNoteFromIntent(){
		int requestCode =getIntent().getIntExtra("requestCode",-1);
		if(requestCode==-1){
			finish();
			return;
		}
		if(requestCode==CHANGE_NOTE){
			int width = mSvgEditor.getWidth();
			int height = mSvgEditor.getHeight();
			mSvgEditor.parse(TransitNoteModel.getTransitNoteModel().getContent(), new byte[]{}, "");
			mSvgEditor.flush(new RectF(0, 0, width, height));
			mSvgEditor.invalidate();
		}
	}
		
    //1.如果没有id集合，则初始化画板,并且分配id，这时候noteId集合中存在一个元素
	//2.如果存在id集合，则加载id的内容
	//2.点击上一步，判断为第一幅，不做调整
	//3.保存的几个时机，1.退出的时候，2.上下翻页的时候保存，或者手动保存//待定。
	//4.id的分配，1.如果noteId集合是空的，则分配一个id到noteId中.否则不产生id
	//

}